package com.example.demo.service.impl;

import com.example.demo.admin.dto.SearchDto;
import com.example.demo.admin.pojo.Dept;
import com.example.demo.admin.pojo.PageResult;
import com.example.demo.mapper.DeptMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.DeptService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 获取全部部门信息
     *
     * @return
     */
    @Override
    public PageResult getAllDept(SearchDto searchDto) {
        PageHelper.startPage(searchDto.getCurrentPage(), searchDto.getPageSize());
        Page<Dept> page = deptMapper.getAllDept(searchDto);
        return PageResult.builder()
                .total(page.getTotal())
                .records(page.getResult())
                .build();
    }

    /**
     * 删除部门
     */
    @Override
    @Transactional
    public void deleteDeptById(Long id) {
        deptMapper.deleteDeptById(id);
        //将属于这个部门的人置空
        userMapper.updateDept(id);
    }

    /**
     * 添加部门
     *
     * @param deptName
     */
    @Override
    public void addDept(String deptName) {
        Dept dept = Dept.builder()
                .updateTime(LocalDateTime.now())
                .createTime(LocalDateTime.now())
                .name(deptName)
                .build();
        deptMapper.addDept(dept);
    }
    /**
     * 编辑部门
     */
    @Override
    public void editDept(String deptName, Long id) {
        Dept dept = Dept.builder()
                .id(id)
                .name(deptName)
                .updateTime(LocalDateTime.now())
                .build();
        deptMapper.editDept(dept);
    }
}
